package moon.excel;

import java.io.InputStream;

import javax.activation.MimeType;

import moon.excel.constants.ExcelConstants;
import moon.excel.reader.IExcelReader;
import moon.excel.reader.impl.DomExcelReader;
import moon.excel.reader.impl.NewExcelEventReader;
import moon.excel.reader.impl.OldExcelEventReader;

public class ExcelImportWrapperBuilder {

	private MimeType mineType = ExcelConstants.MIMETYPE_XLSX;
	private InputStream input;
	private boolean isDomReader = true;

	public static ExcelImportWrapperBuilder creat(InputStream input) {
		return new ExcelImportWrapperBuilder(input);
	}

	private ExcelImportWrapperBuilder(InputStream input) {
		this.input = input;
	}

	public ExcelImportWrapperBuilder setDomReader(boolean isDomReader) {
		this.isDomReader = isDomReader;
		return this;
	}

	public ExcelImportWrapperBuilder setType(String type) {
		if ("xls".equals(type)) {
			mineType = ExcelConstants.MIMETYPE_XLS;
		} else if ("xlsx".equals(type)) {
			mineType = ExcelConstants.MIMETYPE_XLSX;
		} else {
			mineType = null;
		}
		return this;
	}

	public ExcelImportWrapper builder() throws ExcelWraperException {
		if (input == null) {
			throw new ExcelWraperException("输入流不能为空");
		}
		if (mineType == null) {
			throw new ExcelWraperException("无效的excel格式");
		}
		try {
			IExcelReader excelReader = null;
			if (isDomReader) {
				excelReader = new DomExcelReader(mineType, input);
			} else {
				excelReader = ExcelConstants.MIMETYPE_XLS.match(mineType) ? new OldExcelEventReader(input) : new NewExcelEventReader(input);
			}
			return new ExcelImportWrapper(excelReader);
		} catch (Exception e) {
			throw new ExcelWraperException(e);
		}

	}

}
